import sys
sys.setrecursionlimit(10000)
import traceback
from typing import Generator

from PySide6 import QtGui, QtCore
from PySide6.QtWidgets import QFrame

from src.db.obj.save_node import SaveNode
from src.ui.ui.FileRecord_ui import Ui_Form
from src.service import save_node_service
from src.utils.logger import Logger
from src.ui.HoiFileDetail import HoiFileDetail

logger = Logger(__name__)


class FileRecord(QFrame, Ui_Form):

    def __init__(self, parent=None):
        super(FileRecord, self).__init__(parent=parent)
        self.model = None
        self.src_path = None
        self.setupUi(self)

        self.tableView.clicked.connect(lambda x: self.item_click(x))

        self.hoi_windows = []

    def item_click(self, index: QtCore.QModelIndex):
        item = self.model.itemFromIndex(index)
        node: SaveNode = item.data(1)
        hoi_detail_window = HoiFileDetail(hoi=node)
        self.hoi_windows.append(hoi_detail_window)
        hoi_detail_window.show()

    def set_path(self,src_path):
        self.src_path=src_path
        self.refresh()

    def refresh(self):
        if self.src_path is None:
            return
        g: Generator[SaveNode, None, None] = save_node_service.listening_file_record(
            src_path=self.src_path)
        self.model = QtGui.QStandardItemModel()
        self.tableView.setModel(self.model)
        try:
            for i in g:
                item = QtGui.QStandardItem(i.date)
                item.setData(i, 1)
                self.model.appendRow(item)
        except Exception as e:
            logger.i(e)
            traceback.print_exc()